package com.tubeonfire.util;

import java.util.Collections;
import java.util.TreeMap;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.tubeonfire.entity.Tube;
import com.tubeonfire.model.TubeModel;

public class ViewCountHelper {

	private static String cachePrefix = "ViewCount_";
	private static boolean isRegisted = false;
	private static Cache cache = null;

	public static void initCache() {
		if (!isRegisted) {
			isRegisted = true;
			try {
				cache = CacheManager.getInstance().getCacheFactory()
						.createCache(Collections.emptyMap());
			} catch (CacheException e) {
				isRegisted = false;
			}
		}
	}

	@SuppressWarnings("unchecked")
	public static TreeMap<String, Long> getMapIdView() {
		TreeMap<String, Long> result = new TreeMap<String, Long>();
		try {
			initCache();
			String prefix = cachePrefix + "mapIdView";
			if (cache != null) {
				try {
					result = (TreeMap<String, Long>) cache.get(prefix);
					if (result == null)
						result = new TreeMap<String, Long>();
				} catch (Exception e) {
					result = new TreeMap<String, Long>();
				}
			}
			cache.put(prefix, result);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return new TreeMap<String, Long>();
		}
	}

	@SuppressWarnings("unchecked")
	public static void addViewCount(String tubeId) {
		try {
			TreeMap<String, Long> mapIdView = getMapIdView();
			if (mapIdView.containsKey(tubeId)) {
				long view = mapIdView.get(tubeId);
				view++;
				mapIdView.put(tubeId, view);

			} else {
				mapIdView.put(tubeId, (long) 1);
			}
			if (mapIdView.size() > 100) {
				com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
						.getDefaultQueue();
				queue.add(com.google.appengine.api.taskqueue.TaskOptions.Builder
						.withUrl("/task-view-count")
						.method(com.google.appengine.api.taskqueue.TaskOptions.Method.GET));
			} else {
				initCache();
				cache.put(cachePrefix + "mapIdView", mapIdView);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void updateDatabase(TreeMap<String, Long> mapIdView) {
		try {
			for (String id : mapIdView.keySet()) {
				Tube obj = TubeModel.getById(id);
				if (obj != null) {
					long view = mapIdView.get(id);
					obj.setView(view + obj.getView());
					TubeModel.update(obj);
				}
			}
			cache.remove(cachePrefix + "mapIdView");
			com.tubeonfire.model.TubeModel.clearModelCache();
			com.tubeonfire.model.admin.TubeModel.clearModelCache();
			com.tubeonfire.search.TubeSearchModel.clearModelCache();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
